import os
import sys

import xlrd
from hruntools import settings
from hruntools.core.HrunCall import HrunCall
from hruntools.hrunFromExcel import KEY_TESTSUITE, KEY_SHEETSUITE
from hruntools.hruntestcasefilter import objdump2json
from hruntools.parser.hrunParser_excel import HrunParser_excel


class HrunExcel:

    def __init__(self, filePath):
        self.filePath = filePath
        self.workbook = self._loadExcel()

        self.testcaseObj = None
        self.testType = ''

    def _loadExcel(self):
        return xlrd.open_workbook(self.filePath)

    def getWorkdir(self):
        settings.set_WorkDir(os.path.dirname(os.path.abspath(os.path.dirname(self.filePath))))
        return settings.workDir

    def getExcelInfo(self):
        tc = self._parser()
        tcname = tc[0]['config'].get('name', '')

        return {'filename': self.filePath,
                'name': tcname,
                'type': self.testType}

    def _parser(self):
        if self.testcaseObj is not None:
            return self.testcaseObj

        sheetNames = self.workbook.sheet_names()
        hparser = HrunParser_excel(self.getWorkdir())
        if KEY_TESTSUITE in sheetNames:
            # 执行Excel Testsuite模式
            self.testcaseObj = hparser.fromSheet2List_tsuite(self.workbook.sheet_by_name(KEY_TESTSUITE), self.workbook)

            self.testType = KEY_TESTSUITE

            # print(json.dumps(self.hrun.testcaseObj , indent=4, separators=(',', ':'), ensure_ascii=False))
        elif KEY_SHEETSUITE in sheetNames:
            self.testcaseObj = hparser.fromSheet2Dict_sheetsuite(self.workbook.sheet_by_name(KEY_TESTSUITE),
                                                                 self.workbook)
            self.testType = KEY_SHEETSUITE

        else:
            self.testcaseObj = hparser.fromSheet2List_prepare(self.workbook.sheet_by_index(0))

        return self.testcaseObj

    def run(self):

        settings.report_url = ''
        settings.extend_report_type = False
        settings.log_level = 'INFO'

        sys.path.append(settings.workDir)

        try:

            hrun = HrunCall()
            hrun.testcaseObj = self._parser()
            # hrun.callHrun(tcname=hrun.testcaseObj[0]['config']['name'])
            summary = hrun._hrun_run()
            self.submit_report(summary)
        except(Exception):
            print('运行Excel hrun出错===>' + Exception)

    def submit_report(self, summary):
        import requests
        url = ''
        # 'http://127.0.0.1:8000/api/hrunapp/report_add/'
        if url == '':
            #     直接提交
            from hrunapp.helper import save_summary
            save_summary(name=summary['details'][0]['name'],
                         summary=summary,
                         project=1)

            return

        try:

            response = requests.post(url, data={'filepath': self.filePath,
                                                "summary": objdump2json(summary)}, timeout=float(120), verify=False)
            # print(response.content)

        except requests.ConnectTimeout:
            print("post Time out!")
            return None


def listExcelInfo(workDir):
    excelDir = os.path.join(workDir, 'excel')

    excelist = []
    for filename in os.listdir(excelDir):
        # 读取excel文件内容
        excelfile = HrunExcel(os.path.join(excelDir, filename))
        info = excelfile.getExcelInfo()
        info['excelname'] = filename
        excelist.append(info)

    return excelist


def runExcelFile(filePath):
    excelfile = HrunExcel(filePath)
    excelfile.run()
